package datasource

import (
	"fmt"
	"gorm.io/gorm/logger"
	"gorm.io/gorm/schema"
	"log"

	"github.com/bingjian-zhu/gin-vue-admin/common/setting"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

// Db gormDB
type Db struct {
	Conn *gorm.DB
}

// Connect 初始化数据库配置
func (d *Db) Connect() error {
	conf := setting.Config.Database
	//db, err := gorm.Open(dbType, fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8&parseTime=True&loc=Local", user, pwd, host, dbName))
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8&multiStatements=true&parseTime=True&loc=Local",
		conf.User,
		conf.Password,
		conf.Host,
		conf.Port,
		conf.Name)
	//dsn := "root:lSuszj85Tk@tcp(10.70.82.54:32306)/gin-blog-api?charset=utf8mb4&parseTime=True&loc=Local"
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
		SkipDefaultTransaction: false,
		NamingStrategy: schema.NamingStrategy{
			SingularTable: true, // 禁用表名加s
		},
		Logger:                                   logger.Default.LogMode(logger.Info), // 打印sql语句
		DisableAutomaticPing:                     false,
		DisableForeignKeyConstraintWhenMigrating: true, // 禁用创建外键约束
	})
	if err != nil {
		log.Fatal("connecting mysql error: ", err)
		return err
	}
	sqlDB, err := db.DB()
	if err != nil {
		log.Fatal(err.Error())
	}
	sqlDB.SetMaxIdleConns(10)
	sqlDB.SetMaxOpenConns(100)

	d.Conn = db

	log.Println("Connect Mysql Success")

	return nil
}

// DB 返回DB
func (d *Db) DB() *gorm.DB {
	return d.Conn
}
